/**
 * 
 */
package wpmp.security.mgr.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import wcommons.httputils.ResponseUtils;
import wpmp.extjs3.data.Page;
import wpmp.security.client.utils.UserUtils;
import wpmp.security.mgr.Statics;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:42:09 AM Dec 5, 2013
 */
public abstract class DefaultBaseAction<T> extends BaseAction<T> {

	private static final long serialVersionUID = 1L;

	@Override
	public final void prepare() throws Exception {
		// 设置page
		if (page == null) {
			page = new Page();
			page.setLimit(Statics.PAGE_LIMIT);
		}

		// 预留的 与操作入口
		prepare0();
	}

	@Override
	public final T getModel() {
		T entity = getModel0();

		// 设置当前操作用户
		if (entity != null && entity instanceof SysUserMgr) {
			final String loginName = UserUtils.getLoginName(this.getRequest());
			((SysUserMgr) entity).setSysLoginName(loginName);
		}
		return entity;
	}

	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 输出文本
	 * 
	 * @param text
	 * @param headers
	 */
	protected void renderText(String text, String... headers) {
		ResponseUtils.renderText(getResponse(), text, headers);
	}

	/**
	 * 输出html
	 * 
	 * @param html
	 * @param headers
	 */
	protected void renderHtml(String html, String... headers) {
		ResponseUtils.renderHtml(getResponse(), html, headers);
	}

	/**
	 * 输出json
	 * 
	 * @param jsonString
	 * @param headers
	 */
	protected void renderJson(String jsonString, String... headers) {
		ResponseUtils.renderJson(getResponse(), jsonString, headers);
	}

	/**
	 * 此方法替代 ModelDriven.getModel()
	 * 
	 * @return
	 */
	protected abstract T getModel0();

	/**
	 * 此方法替代 Preparable.prepare()
	 * 
	 * @throws Exception
	 */
	protected void prepare0() throws Exception {
	}
}
